import re

class Hidden_Iframe(object):
    """
    extract features from the iframe like hidden or cross domain src value
    """
    def __init__(self,filename):
	#initialise filename
	self.parentURL 			= filename

    def i_score(self,attrs):
	"""assign score to the iframe"""
	self.score = 0
	attrname = []
	attrvalue = []
        for attr in attrs:
	    attrname.append(attr[0])
	    attrvalue.append(attr[1])
	hidden_iframe,chk_domain = self.is_hidden(attrname,attrvalue)
	# all this has to be collected into one feature and self.scored. score=iframe type+link domain, as written below.
	#hidden iframe+Xdomain link=2+1, hidden iframe+same domain link=2+0, visible iframe+X domain link=0+1, visible iframe+same domain link=0+0
	if hidden_iframe == 2:
	    self.score += 2
	else:
	    self.score += 0

	if chk_domain:
	    self.score += 1
	else:
	    self.score += 0  
	return self.score,self.URL

    def ialert(self):
	print self.score,self.URL,"in ialert"	
	return str(self.score)+self.URL

    def is_hidden(self,name,value):
	"""returns 1 when hidden, 0.5,chosen arbitralily, when unnoticeable, 0 when not hidden"""	
	h,w,f = 1,1,0
	for j in range(len(name)):
            if name[j].lower() == "style":
	        if re.search("visibility:hidden|display:none",value[j].lower()):
                    hidden = 1
            if name[j].lower() == "height":
		if 'px' in value[j]: h = int(value[j].rstrip('px'))
		elif '%' in value[j]: h = int(value[j].rstrip('%'))
		else: h = int(value[j])
            if name[j].lower() == "width":
	        if 'px' in value[j]: w = int(value[j].rstrip('px'))
                elif '%' in value[j]: w = int(value[j].rstrip('%'))
                else: w = int(value[j])
  
            if name[j].lower() == "frameborder":
	        if 'px' in value[j]: f = int(value[j].rstrip('px'))
                elif '%' in value[j]: f = int(value[j].rstrip('%'))
            	elif "no" in value[j].lower(): f = 0			#some web pages gave error, though I haven't found this in usage, anyways.
	        else: f = int(value[j])
              
	    if name[j].lower() == "src":
		try:
		    self.URL = value[j]	
		except:
		    self.URL = ""
		domain = self.check_src()
	#to deal with the error raised from 118114.com..
	if name.count("src") == 0:
	    print "it had no src"
	    self.URL = ""
	    domain = False
        if (h*w < 2) and f == 0:
            hidden = 2
	else:
	    hidden = 0
        return hidden,domain

    def check_src(self):
	"""check if domain of iframe src is different from the parent domain, this is hidden and called from is_hidden"""
	from urlparse import urlparse
	p_tuple = urlparse(self.parentURL)
	i_tuple = urlparse(self.URL)	
	p_domain = p_tuple[1].split(".") 			#split returns a list of the complete address separated on dot, for instanse
	i_domain = i_tuple[1].split(".")			#cs.yale.edu - ['cs','yale','edu']
	# the last element in the list is the highest in the domain tree. and the length of the domain tree is a clear identifier of cross domain.
	#eg - cs.iitk.ac.in and cs.yale.edu are completely different.
	if i_domain.count('') >= 1:
	    return False		#this is the check for the relative URL ; always in the same domain though donot mention domain explicitly...
	else:
	    if len(p_domain) != len(i_domain):
	        return True
	    else:
	        #now we got to check each element for match, starting from the end, that is the top of the tree.
	        hostnames = zip(p_domain,i_domain)
		l = len(hostnames)
	        if hostnames[:l]:
	            for x in hostnames[:3]:
	    	        if x[0].lower() == x[1].lower(): pass
	    	        else: return True
	    	    return False
